<template>
  <el-select
    :modelValue="modelValue"
    @update:modelValue="updateValue"
    :placeholder="placeholder"
    :clearable="clearable"
    :loading="loading"
    filterable
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.username"
      :value="item.id"
    >
      <div class="user-option">
        <span>{{ item.username }}</span>
        <span class="user-id">ID: {{ item.id }}</span>
      </div>
    </el-option>
  </el-select>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch, onMounted } from "vue";
import request from "@/utils/request";

const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: null,
  },
  placeholder: {
    type: String,
    default: "请选择用户",
  },
  clearable: {
    type: Boolean,
    default: true,
  },
});

const emit = defineEmits(["update:modelValue", "change"]);

// 更新值的方法，用于v-model
const updateValue = (value) => {
  emit("update:modelValue", value);
  emit("change", value);
};

const options = ref([]);
const loading = ref(false);
const allUsers = ref([]);

// 加载所有用户
const loadAllUsers = async () => {
  loading.value = true;
  try {
    // 优先尝试使用 /user/all 接口
    try {
      const response = await request({
        url: "/user/all",
        method: "get",
      });

      if (response.data && Array.isArray(response.data)) {
        allUsers.value = response.data;
        options.value = response.data;
        return;
      }
    } catch (error) {
      console.log("尝试获取所有用户出错，将使用列表接口:", error);
    }

    // 如果 /user/all 接口不可用，则使用 /user/list 接口并设置较大的页面大小
    const response = await request({
      url: "/user/list",
      method: "get",
      params: {
        pageNum: 1,
        pageSize: 1000, // 获取大量用户
      },
    });

    if (response.data && response.data.list) {
      allUsers.value = response.data.list;
      options.value = response.data.list;
    }
  } catch (error) {
    console.error("获取所有用户出错:", error);
  } finally {
    loading.value = false;
  }
};

// 当有默认选中的用户ID时，确保该用户在选项中
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && allUsers.value.length > 0) {
      // 如果已加载所有用户，检查选中的用户是否在列表中
      const foundUser = allUsers.value.find((user) => user.id == newVal);
      if (!foundUser) {
        console.warn(`用户ID ${newVal} 在已加载的用户列表中未找到`);
      }
    }
  },
  { immediate: true }
);

// 组件挂载时加载所有用户
onMounted(() => {
  loadAllUsers();
});
</script>

<style scoped>
.user-option {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.user-id {
  color: #909399;
  font-size: 0.9em;
}
</style>
